package com.psjj.privilege.dao;

import com.psjj.privilege.po.User;
import com.psjj.privilege.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDao {
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtils.getDataSource());

    public User queryUserByNameAndPwd(String username, String pwd) throws SQLException {
        User user = queryRunner.query("select * from t_user where username=? and pwd=?",
                new BeanHandler<User>(User.class), username, pwd);
        return user;
    }

    public int getCount(String username) throws SQLException {
        Long result = queryRunner.query("select count(*) from t_user where username like ?", new ScalarHandler<Long>(), username);
        return result.intValue();
    }

    public List<User> getPage(String username, int begin, int pageSize) throws SQLException {
        List<User> list = queryRunner.query("select * from t_user where username like ? order by uid desc limit ?,?",
                new BeanListHandler<User>(User.class),username, begin, pageSize);
        return list;
    }

    public int add(User user) throws SQLException {
        queryRunner.update("insert into t_user(username,pwd,phone) values(?,?,?)",user.getUsername()
        ,user.getPwd(),user.getPhone());
        //返回添加之后的自增id值
        Long uid = queryRunner.query("select LAST_INSERT_ID()", new ScalarHandler<Long>());
        return uid.intValue();
    }

    public void addUidAndRid(int uid, int rid) throws SQLException {
        queryRunner.update("insert into t_user_role(userid,roleid) values(?,?)",uid,rid);
    }

    public User queryUserByUid(int uid) throws SQLException {
        User user = queryRunner.query("select * from t_user where uid=?",
                new BeanHandler<User>(User.class), uid);
        return user;
    }

    public void editUser(User user) throws SQLException {
        queryRunner.update("update t_user set username=?,phone=? where uid=?",user.getUsername()
        ,user.getPhone(),user.getUid());
    }

    public void clearUserIdJoinRoleIdByUserId(Integer uid) throws SQLException {
        queryRunner.update("delete from t_user_role where userid=?",uid);
    }

    public void updateUserStatusByUid(int uid,int status) throws SQLException {

        queryRunner.update("update t_user set status=? where uid=?",status,uid);
    }

    public void updatePwdByUid(int uid, String pwd) throws SQLException {
        queryRunner.update("update t_user set pwd=? where uid=?",pwd,uid);
    }

    public void updatePwdByUsername(String username, String pwd) throws SQLException{
        queryRunner.update("update t_user set pwd=? where username=?",pwd,username);
    }
}
